import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:x_core/x_core.dart';
import 'package:x_module_copy/constant/copy_api_constant.dart';
import 'package:x_module_copy/pages/copy/copy_state.dart';
import 'package:x_project/entity/login_entity.dart';
import 'package:x_project/x_project.dart';

/// Created by XieXin on 2022/8/23.
/// 业务逻辑处理
class CopyController extends GetxController {
  CopyState state = CopyState();
  late TextEditingController mobileController;
  late TextEditingController passwordController;
  late FocusNode nodeText1;
  late FocusNode nodeText2;

  @override
  void onInit() {
    super.onInit();
    mobileController = TextEditingController();
    passwordController = TextEditingController();
    nodeText1 = FocusNode();
    nodeText2 = FocusNode();
    mobileController.addListener(_verify);
    passwordController.addListener(_verify);
  }

  void _verify() {
    state.username = mobileController.text;
    state.password = passwordController.text;
    bool isClick = false;
    if (state.username.isNotEmpty &&
        state.username.length == 11 &&
        state.password.isNotEmpty &&
        state.password.length >= 6) {
      isClick = true;
    } else {
      isClick = false;
    }

    /// 状态不一样在刷新，避免重复不必要的setState
    if (state.isClickLogin != isClick) {
      state.isClickLogin = isClick;
      update();
    }
  }

  void login({required String mobile, required String password}) =>
      request(() async {
        Map<String, dynamic> map = {
          "mobile": mobile,
          "password": password,
        };
        var login = await DioHolder().post(CopyApiConstant.login, data: map);
        state.login = LoginEntity.fromJson(login);
        LogUtil.v(state.login.toString());
        update();
      });
}
